﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Craftsman.xCoronavirus.Domain;
using Craftsman.xCoronavirus.Domain.Entities;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace Craftsman.xCoronavirus.WebApi.Controllers
{
    [Route("api/importdata")]
    [ApiController]
    public class ImportDataController : Controller
    {
        private IHostingEnvironment hostingEnv;
        public IQuestionnaireService _questionnairService { get; set; }

        public ImportDataController(IHostingEnvironment env, IQuestionnaireService questionnairService)
        {
            this.hostingEnv = env;
            _questionnairService = questionnairService;
        }

        [HttpPost]
        public JsonResult UploadFilesAjax()
        {
            JArray lst = new JArray();
            JObject jsonResult = new JObject();
            int result = 0;
            //long size = 0;
            string fileNamePath = string.Empty;
            try
            {
                var files = Request.Form.Files;
                foreach (var file in files)
                {
                    string fileName = DateTime.Now.ToString("MMddHHmmss") + file.FileName;
                    fileNamePath = Path.Combine("upload", fileName);
                    string serverUrl = Request.HttpContext.Connection.LocalIpAddress + ":" + Request.HttpContext.Connection.LocalPort + @"/upload/DeviceImage.jpg";


                    //保存文件
                    //物理路径 
                    string SavePath = Path.Combine(hostingEnv.ContentRootPath, fileNamePath);
                    using (FileStream fs = new FileStream(SavePath, FileMode.CreateNew))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                        result = 1;
                    }

                    DataTable dt = new DataTable();
                    if (file.FileName.Contains(".csv"))
                    {
                        dt = NPOIHelper.ReadCSVToDataTable(SavePath); //乱码有问题
                    }
                    else
                    {
                        dt = NPOIHelper.ReadExcelToDataTable(SavePath);
                    }


                    List<ContactsKey> ContactsColumns = new List<ContactsKey>();//联系人 
                    List<MaterialDemandsKey> MaterialDemandsColumns = new List<MaterialDemandsKey>(); //物资 


                    ContactsKey contactsKey = new ContactsKey();
                    MaterialDemandsKey materialDemandsKey = new MaterialDemandsKey();

                    foreach (DataColumn item in dt.Columns)
                    {
                        if (item.ColumnName.Contains("Q3_A")) //联系人
                        {
                            if (item.ColumnName.Contains("_A1_open"))
                            {
                                contactsKey.Name = item.ColumnName;
                            }
                            else if (item.ColumnName.Contains("_A2_open"))
                            {
                                contactsKey.Phone = item.ColumnName;
                            }
                            else if (item.ColumnName.Contains("_A4_open"))
                            {
                                contactsKey.Wechat = item.ColumnName;
                                ContactsColumns.Add(contactsKey);
                                contactsKey = new ContactsKey();
                            }

                        }

                        if (item.ColumnName.Contains("Q5_A"))//物资
                        {
                            if (item.ColumnName.Contains("_A1_open"))
                            {
                                materialDemandsKey.Name = item.ColumnName;
                            }
                            else if (item.ColumnName.Contains("_A3_open"))
                            {
                                materialDemandsKey.Quantity = item.ColumnName;
                            }
                            else if (item.ColumnName.Contains("_A4_open"))
                            {
                                materialDemandsKey.Unit = item.ColumnName;
                            }
                            else if (item.ColumnName.Contains("_A5_open"))
                            {
                                materialDemandsKey.Level = item.ColumnName;
                                MaterialDemandsColumns.Add(materialDemandsKey);
                                materialDemandsKey = new MaterialDemandsKey();
                            }

                        }

                    }


                    foreach (DataRow dr in dt.Rows)
                    {
                        #region questionnaire 问卷信息表

                        if (dr["seq"] == null) { continue; }

                        string formCode = dr["seq"].ToString();

                        Questionnaire entity = _questionnairService.GetQuestionnaireByFormCode(formCode);
                        if (entity != null) { continue; }//已存在

                        entity = new Questionnaire();

                        int status = 0;
                        //int.TryParse(dr["status"].ToString(), out status); //固定 0

                        entity.Status = (QuestionnaireStatus)status; //状态 
                        DateTime dt_start = DateTime.Now;
                        DateTime dt_end = DateTime.Now;

                         
                        DateTime.TryParse(dr["start"].ToString(), out dt_start);
                        DateTime.TryParse(dr["finish"].ToString(), out dt_end);

                        entity.StartTime = dt_start;//开始时间,
                        entity.EndTime = dt_end; //结束时间,
                        entity.FormCode = formCode;//医院问卷编号,
                        entity.CreatedTime = DateTime.Now;//创建时间

                        #endregion

                        #region questionnaire_hospital 问卷信息-医院部分

                        int staff_count = 0;
                        int.TryParse(dr["Q1_A5_open"].ToString(), out staff_count);

                        if (entity.Hospital == null) { entity.Hospital = new QuestionnaireHospital(); }

                        entity.Hospital.QuestionnaireId = entity.Id;//问卷id（FK）
                        entity.Hospital.Name = dr["Q1_A1_open"].ToString(); //医院名称
                        entity.Hospital.StaffCount = staff_count;//员工数量
                        entity.Hospital.Province = dr["Q2_A1_open"].ToString(); //省份
                        entity.Hospital.City = dr["Q2_A2_open"].ToString(); //城市
                        entity.Hospital.Region = dr["Q2_A3_open"].ToString(); //区域/县
                        entity.Hospital.DetailedAddress = dr["Q2_A4_open"].ToString(); //详细地址

                        entity.Hospital.DirectAccept = int.Parse(dr["Q4"].ToString());   //是否可以直接接收物资 *
                        entity.Hospital.StaffCard = dr["Q6_A1_open"].ToString(); //医师工作证
                        entity.Hospital.StaffCardImage = dr["Q6_A1_open"].ToString(); //医师工作证图片链接
                        entity.Hospital.Certificate = dr["Q7_A1_open"].ToString(); //医院证明
                        entity.Hospital.CertificateIamge = dr["Q7_A1_open"].ToString(); //医院证明图片链接
                        //remark varchar(500) //备注


                        #endregion

                        #region questionnaire_material_demand 问卷信息-物资需求 

                        if (entity.MaterialDemands == null) { entity.MaterialDemands = new List<QuestionnaireMaterialDemand>(); }

                        foreach (MaterialDemandsKey mdkey in MaterialDemandsColumns)
                        {
                            QuestionnaireMaterialDemand qmd = new QuestionnaireMaterialDemand();
                            qmd.QuestionnaireId = entity.Id;// 问卷编号
                            if (dr[mdkey.Name] == null || dr[mdkey.Name].ToString().Trim() == "") { continue; }
                            qmd.DemandName = dr[mdkey.Name].ToString(); //物资名称
                            qmd.Quantity = int.Parse(dr[mdkey.Quantity].ToString());         //需求物品数量
                            qmd.Unit = dr[mdkey.Unit].ToString();  //单位

                            string strLevel = dr[mdkey.Level].ToString(); 
                            int intLevel = 0;
                            int.TryParse(strLevel.Substring(0, 1), out intLevel);

                            qmd.Level = intLevel; //优先级
                            //qmd.Remark  //备注

                            entity.MaterialDemands.Add(qmd);
                        }

                        #endregion

                        #region questionnaire_contact 问卷联系人

                        if (entity.Contacts == null) { entity.Contacts = new List<QuestionnaireContact>(); }

                        foreach (ContactsKey ckey in ContactsColumns)
                        {
                            QuestionnaireContact qc = new QuestionnaireContact();
                            qc.QuestionnaireId = entity.Id; //问卷Id
                                                           //qc.VolunteerName  //志愿者
                            if (dr[ckey.Name] == null || dr[ckey.Name].ToString().Trim() == "") { continue; }
                            qc.HospitalContact = dr[ckey.Name].ToString(); //联系人
                            qc.Phone = dr[ckey.Phone].ToString();  //联系电话
                            qc.Wechat = dr[ckey.Wechat].ToString();  //微信
                                                                     //qc.Remark //备注
                            entity.Contacts.Add(qc);
                        }
                        #endregion

                        _questionnairService.CreateQuestionnaire(entity);
                    }



                }
                //string url = Request.HttpContext.Connection.RemoteIpAddress.ToStringExt()+":"+ Request.HttpContext.Connection.RemotePort.ToStringExt();
                jsonResult.Add("Result", result);
            }
            catch (Exception ex)
            {
                jsonResult.Add("Result", result);
            }
            return Json(jsonResult);
        }
    }

    public class ContactsKey
    {
        /// <summary>
        ///  联系人姓名
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 联系电话
        /// </summary>
        public string Phone { get; set; }

        /// <summary>
        /// 微信
        /// </summary>
        public string Wechat { get; set; }

    }
    public class MaterialDemandsKey
    {
        /// <summary>
        ///  物资名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 需求物品数量
        /// </summary>
        public string Quantity { get; set; }

        /// <summary>
        /// 单位
        /// </summary>
        public string Unit { get; set; }

        /// <summary>
        /// 优先级情况
        /// </summary>
        public string Level { get; set; }
    }
}